package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import com.itheima.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @GetMapping("/list")
    public R<Object> addDish(Integer type) {

        System.out.println("----------"+type);
        List<Category> byTypeCategory = categoryService.getByTypeCategory(type);
       if (byTypeCategory == null){
           R.error("当前没有菜品分类");
       }
        return R.success(byTypeCategory);
    }


    @DeleteMapping()
    public R<Object> deleteCategory( Long id){
        System.out.println(id);
        Integer result = categoryService.deleteCategory(id);
        System.out.println(result);
        if (result ==null){
          return R.error("删除失败");
        }

        return R.success("删除成功");
    }

    @PutMapping()
    public R<Object> updateCategory(@RequestBody Category category,
                               HttpServletRequest request){

        System.out.println(category);
        Integer id =(Integer) request.getSession().getAttribute("id");
        long lId = Long.parseLong(String.valueOf(id));
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(lId);
        Integer result = categoryService.updateCategory(category);
        if (result == null){
            return R.error("修改失败");
        }
            return R.success("修改成功");
    }


    @PostMapping()
    public R<Object> addCategory(HttpServletRequest request,
                            @RequestBody Category category){
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        Integer id =(Integer)request.getSession().getAttribute("id");
        long lId = Long.parseLong(String.valueOf(id));
        category.setCreateUser(lId);
        category.setUpdateUser(lId);
        System.out.println(category);
        Integer result = categoryService.addaddCategory(category);
        if (result == null){
            return  R.error("添加失败");
        }
            return R.success("添加成功");
    }


    @GetMapping("/page")
    public R<Object> getCategory(Integer page, Integer pageSize) {
        IPage<Category> category = categoryService.getCategory(page, pageSize);
        if (category == null) {
            return R.error("获取数据失败");
        }
        return R.success(category);
    }

}
